#include <cserver/restapi.h>
#include <boost/log/trivial.hpp>
#include <boost/lexical_cast.hpp>
#include <pqxx/transaction.hxx>
#include <boost/format.hpp>

#include <sstream>

namespace csrv{ namespace webcmd{
	static const char* K_this_command= "api/v1/hydrant/area_all";

	void hydrant_area_all(Request& req, pqxx::connection& dbconn, SessionContext& , const std::string& /*cmd*/ ){
		auto query = parseQuery(req.getParam("QUERY_STRING"));
		auto& callback = query["callback"];
		auto& from_s = query["from"];
		auto& count_s = query["count"];
		unsigned int from = from_s.empty() ? unsigned(0): boost::lexical_cast<unsigned>(from_s);
		unsigned int limit = count_s.empty() ? unsigned(2000): boost::lexical_cast<unsigned>(count_s);
		limit = std::min(limit, unsigned(2000));
		limit = std::max(limit, unsigned(1));

		StreamGroup sg(req);
		auto& fout = sg.fout;
		response_header(sg.fout, 200);
		if (!callback.empty()) sg.fout << callback << "(";

		pqxx::work w(dbconn);
		auto gps =  result2json(w.prepared("get_hydrant_gps_rect").exec(), 0);
		gps.pop_back();
		gps.erase(gps.begin()); //remove around "[]"


#if 1
		fout << boost::format(R"({"func":"hydrant/area",
"args":{},
"ret":{"success":true, "message":"",
"total":%1%,
"value":{"gps": %2%, "items":)") % TotalCount(w, "get_hydrant_by_area_total2").result() % gps;
#endif

		auto result = w.prepared("get_hydrant_by_area2")(limit)(from).exec();
		fout << result2json(result, 3);

		fout << "}}}";
		if (!callback.empty()) sg.fout << ")";
	}
}

static CommandAddHelper k_registerHandler("GET", webcmd::K_this_command, &webcmd::hydrant_area_all);
}


